package com.singerw.Interceptor;

import com.singerw.annotations.UserId;
import com.singerw.annotations.UserName;
import com.singerw.utils.JwtUtils;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * 通过声明对应注解，拿到想要的对应信息。
 */
public class InfoResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(UserId.class) || parameter.hasParameterAnnotation(UserName.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws UnsupportedEncodingException {
        String authorization = webRequest.getHeader("Authorization");
        String userId = JwtUtils.getUserId(authorization);
        if (parameter.hasParameterAnnotation(UserId.class)){
            String team = new String(URLDecoder.decode(webRequest.getHeader("team"), "utf-8"));
            if(team != null && !team.equals("null")){
                return "user_team/" + team;
            }
            String recycle = webRequest.getHeader("recycle");
            if(recycle != null && !recycle.equals("null")){
                return "user_recycle/" + userId;
            }
            String private_ = webRequest.getHeader("private");
            System.out.println(private_);
            if(private_ != null && !private_.equals("null")){
                return "user_private/" + userId;
            }
            String prefix = parameter.getParameterAnnotation(UserId.class).prefix();
            return prefix + userId;
        }else if( parameter.hasParameterAnnotation(UserName.class)){
            return JwtUtils.getUsername(authorization);
        }
        return null;


    }
}
